$(function () {
	$('#courseStructureDataGrid').hide();
	$('#courseDataGrid').hide();
	$('#textbookDataGrid').hide();
    initCourseStructureGridData();
    initCourseGridData();
    initTextbookGridData();
    initShowRegion();
    initOther();
});

function initCourseStructureGridData() {
    $('#courseStructureDataGrid').datagrid({
    	title: "课程结构",
        fitColumns: true,
        fit: true,
        idField: 'Id',
        sortName: 'Id',
        sortOrder: 'desc',
        rownumbers: true,
        singleSelect: true,
        border: false,
        url: "courseStructure/all?page=1&rows=100000",
        toolbar: [
            {
                text: '新增',
                iconCls: 'icon-add',
                handler: function () {
                    showOperateCourseStructureDialog("新增");
                }
            },
            '-',
            {
                text: '刷新',
                iconCls: 'icon-reload',
                handler: function () {
                    gridReload($('#courseStructureDataGrid'));
                }
            }
        ],
        columns: [
            [
                {field: 'studyArea', title: '学习领域', align: 'center', width: 30},
                {field: 'studySubject', title: '学习科目', align: 'center', width: 30},
                {field: 'studyType', title: '类型', align: 'center', width: 15,
                    formatter: function (value, row, index) {
                        return studyType[value - 1];
                    }
                },
                {field: 'operation', title: '操作', align: 'center', width: 40,
                    formatter: function (value, row, index) {
                        return "<a class='up' onclick='showOperateCourseStructureDialog(\"修改\", " + index + ");'>修改</a>" +
                            "<a class='re' onclick='showDeleteCourseStructureDialog(" + index + ");'>删除</a>";
                    }
                }
            ]
        ],
        onSelect: function(rowIndex, rowData) {
        	$('#courseDataGrid').datagrid({
        		title : "课程结构[" + rowData.studySubject + "]包括的课程/模块",
				url : "course/in-coursestructure/" + rowData.id
        	});
        	
        },
        rowStyler: function(index,row){  
            if (index % 2 == 1){  
                return 'background-color:#FFF8DC;';  
            }  
        },
        onLoadSuccess: function() {
        	changeStyle();
        	$('#courseStructureDataGrid').show();
        	$('#courseDataGrid').show();
        	$('#textbookDataGrid').show();
        }
    });
}

//============================ //
function changeStyle() {
	$('.re').linkbutton({  
	    iconCls: 'icon-remove',
	    plain: true
	});  
	$('.up').linkbutton({  
	    iconCls: 'icon-edit',
	    plain: true
	});  
	$('.cn1').panel({  
	  width:540,
	  height:200,
	  title: '课程评价方法' 
	});   
	$('.cn2').panel({  
		  width:540,
		  height:200,
	  title: '课程内容描述' 
	});  
	$('.cn3').panel({  
		  width:540,
		  height:200,
	  title: '课程要求' 
	});   
	$('.cn4').panel({  
		  width:540,
		  height:200,
	  title: '课程备注程人数要求' 
	});  
	$('.cn5').panel({  
		  width:540,
		  height:200,
	  title: '课程人数要求' 
	});  
	$('.cn6').panel({  
		  width:540,
		  height:200,
	  title: '课程开课时段' 
	});    
}

function initOther() {
    extendValiateboxType();
    $('#studyType').combobox({
        valueField: 'id',
        textField: 'text',
        panelHeight: 88,
        data: [
            {
                "id": 1,
                "text": studyType[0]
            },
            {
                "id": 2,
                "text": studyType[1]
            }
        ]
    });
    
}
//###########################################
function showOperateCourseStructureDialog(operateName, index) {
    $('#oldIdNo').remove();
    $('#operateCourseStructureDialog').dialog({
        title: operateName + "课程结构信息",
        width: 256,
        height: 200,
        modal: true,
        buttons: [
            {
                text: operateName,
                handler: function (params) {
                    operateCourseStructure(operateName);
                }
            },
            {
                text: '取消',
                handler: function () {
                    $('#operateCourseStructureDialog').dialog('close');
                }
            }
        ]
    });
    clearCourseStructureOldData();
    if (operateName == '修改') {
        var courseStructure = getSelectedRow('courseStructureDataGrid', index);
        $("#courseStructureId").val(courseStructure.id);
        $("#studyArea").val(courseStructure.studyArea);
        $("#studySubject").val(courseStructure.studySubject);
        $("#studyType").combobox('select', courseStructure.studyType);
        $('#operateCourseStructureDialog').append("<span id='oldIdNo'><span id='sa'>" + courseStructure.studyArea + "</span><span id='ss'>" + courseStructure.studySubject + "</span></span>");
    }
}

function clearCourseStructureOldData() {
    $("#courseStructureId").val("");
    $("#studyArea").val("");
    $("#studySubject").val("");
    $("#studyType").combobox('setValue', 1);
}

function operateCourseStructure(operationName) {
    var $studyArea = $('#studyArea');
    var $studySubject = $('#studySubject');
	if ($.trim($studyArea.val()).length == 0 || $.trim($studySubject.val()).length == 0) {
		$.messager.alert("警告", "请确保红色*内容不为空！", "warning");
		return;
	}
    var tempUrl = "courseStructure/add";
    if (operationName === '修改') {
        tempUrl = "courseStructure/update";
    } else {
        $("#courseStructureId").val(-999);
    }
	if ($('#oldIdNo').text() != null && $('#sa').text() == $("#studyArea").val() && $('#ss').text() == $("#studySubject").val()) {
		 $.ajax({
	         type: 'POST',
	         data: {
	             "id": $("#courseStructureId").val(),
	             "studyArea": $("#studyArea").val(),
	             "studySubject": $("#studySubject").val(),
	             "studyType": $("#studyType").combobox('getValue'),
	             "studyCredit": $("#studyCredit").val()
	         },
	         url: tempUrl,
	         dataType: "json",
	         cache: false,
	         error: function (jqXHR, textStatus, errorThrown) {
	             $.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
	         },
	         success: function (data) {
	             if (true == data.result) {
	                 $.messager.alert("操作提示", "课程结构信息操作完成！", "info", function () {
	                     $('#operateCourseStructureDialog').dialog('close');
	                     gridReload($('#courseStructureDataGrid'));
	                 });
	             }
	         }
	     });
	} else {
		$.ajax({
	        type: 'POST',
	        data: { "studyArea": $("#studyArea").val(), "studySubject": $("#studySubject").val() },
	        url: "courseStructure/exists",
	        dataType: "json",
	        cache: false,
	        success: function (data) {
	            if (true == data.result) {
	        		$.messager.alert("警告", "课程结构已经存在！", "warning");
	            } else {
	                $.ajax({
	                    type: 'POST',
	                    data: {
	                        "id": $("#courseStructureId").val(),
	                        "studyArea": $("#studyArea").val(),
	                        "studySubject": $("#studySubject").val(),
	                        "studyType": $("#studyType").combobox('getValue'),
	                        "studyCredit": $("#studyCredit").val()
	                    },
	                    url: tempUrl,
	                    dataType: "json",
	                    cache: false,
	                    error: function (jqXHR, textStatus, errorThrown) {
	                        $.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
	                    },
	                    success: function (data) {
	                        if (true == data.result) {
	                            $.messager.alert("操作提示", "课程结构信息操作完成！", "info", function () {
	                                $('#operateCourseStructureDialog').dialog('close');
	                                gridReload($('#courseStructureDataGrid'));
	                            });
	                        }
	                    }
	                });
	            }
	        }
	    });
	}
}

function showDeleteCourseStructureDialog(index) {
    $.messager.confirm("警告", "确定删除选中课程结构？", function (data) {
        if (data) {
        	var courseStructure = getSelectedRow('courseStructureDataGrid', index);
        	$.ajax({
        		type: 'POST',
        		data: {
        			"courseStructureId": courseStructure.id
        		},
        		url: "courseStructure/remove",
        		dataType: "json",
        		cache: false,
        		error: function (jqXHR, textStatus, errorThrown) {
        			$.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
        		},
        		success: function (data) {
        			if (true == data.result) {
    					gridReload($('#courseStructureDataGrid'));
        			} else {
                        $.messager.alert("操作提示", "删除课程结构信息异常！");
                    }
        		}
        	});
        }
    });
}
//##########################################################
function initCourseGridData() {
    $('#courseDataGrid').datagrid({
   	 	title: "课程/模块",
        fitColumns: false,
        fit: true,
        idField: 'Id',
        sortName: 'Id',
        sortOrder: 'desc',
        rownumbers: false,
        singleSelect: true,
        border: false,
        toolbar: [
            {
                text: '新增',
                iconCls: 'icon-add',
                handler: function () {
                    showOperateCourseDialog("新增");
                }
            }
        ],
//        columns: [
//            [
//                {field: 'id', hidden:true}, // datagrid多选 getSelections ，必须使用idFiled这个字段
//                {field: 'courseName', title: '课程名称', align: 'center', width: 80},
//                {field: 'courseCode', title: '课程编码', align: 'center', width: 80},
//                {field: 'operation', title: '操作', align: 'center', width: 80,
//                    formatter: function (value, row, index) {
//                        return "<a class='up' onclick='showOperateCourseDialog(\"修改\", " + index + ");'>修改</a>" +
//                            "<a class='re' onclick='showDeleteCourseDialog(" + index + ");'>删除</a>";
//                    }
//                }
//            ]
//        ],
        onSelect: function(rowIndex, rowData) {
//            $.ajax({
//                type: "POST",
//                url : "textbook/in-courses/" + rowData.id,
//                dataType: "json",
//                cache: false,
//                success: function (data) {
//                    $("#textbookDataGrid").datagrid("loadData", data);
//                }
//            });
        	$('#textbookDataGrid').datagrid({
        		title : "课程[" + rowData.courseName + "]包括的教材",
        		url : "textbook/in-courses/" + rowData.id
        	});
        	$('#courseEvaluationShow').val(rowData.courseEvaluation).attr("disabled", true);
        	$('#courseContentShow').val(rowData.courseContent).attr("disabled", true);
        	$('#courseRequirementShow').val(rowData.courseRequirement).attr("disabled", true);
        	$('#courseCommentShow').val(rowData.courseComment).attr("disabled", true);
        	$('#courseNumberShow').val(rowData.courseNumber).attr("disabled", true);
        	$('#coursePeriodShow').val(rowData.coursePeriod).attr("disabled", true);
        },
        rowStyler: function(index,row){  
            if (index % 2 == 1){  
                return 'background-color:#FFF8DC;';  
            }  
        }, 
        view: detailview,
        onExpandRow:function(index, row){
            $('#courseDataGrid').datagrid('fixDetailRowHeight', index);
        },
        detailFormatter:function(index,row){ 
        	return '<div class="cn1">' + row.courseEvaluation + '</div>' + 
			       '<div class="cn2">' + row.courseContent + '</div>' + 
			       '<div class="cn3">' + row.courseRequirement + '</div>' + 
			       '<div class="cn4">' + row.courseComment + '</div>' + 
			       '<div class="cn5">' + row.courseNumber + '</div>' + 
			       '<div class="cn6">' + row.coursePeriod + '</div>';
        }, 
        onLoadSuccess: function() {
        	changeStyle();
        }
    });
}

function showOperateCourseDialog(operateName, index) {
    $('#oldIdNo').remove();
    var courseStructure = $('#courseStructureDataGrid').datagrid('getSelected');
    if (courseStructure == null) {
		$.messager.alert("警告", "请首先选择一个课程结构！", "warning");
    	return;
    }
    $('#operateCourseDialog').dialog({
        fit:false,
        inline:false,
        title: operateName + "课程信息",
        width: 580,
        height: 400,
        modal: true,
        buttons: [
            {
                text: operateName,
                handler: function (params) {
                    operateCourse(operateName);
                }
            },
            {
                text: '取消',
                handler: function () {
                    $('#operateCourseDialog').dialog('close');
                }
            }
        ]
    });
    clearCourseOldData();
    if (operateName == '修改') {
        var course = getSelectedRow('courseDataGrid', index);
        $("#courseId").val(course.id);
        $("#courseName").val(course.courseName);
        $("#courseCode").val(course.courseCode);
        $("#courseEvaluation").val(course.courseEvaluation);
        $("#courseContent").val(course.courseContent);
        $("#courseRequirement").val(course.courseRequirement);
        $("#courseComment").val(course.courseComment);
        $("#courseNumber").val(course.courseNumber);
        $("#coursePeriod").val(course.coursePeriod);
        $("#studyCredit").val(course.studyCredit);
        $('#operateCourseDialog').append("<span id='oldIdNo'>" + course.courseName + "</span>");
    }
}

function clearCourseOldData() {
    $("#courseId").val("");
    $("#courseName").val("");
    $("#courseCode").val("");
    $("#studyCredit").val("");
    $("#courseEvaluation").val("");
    $("#courseContent").val("");
    $("#courseRequirement").val("");
    $("#courseComment").val("");
    $("#courseNumber").val("");
    $("#coursePeriod").val("");
}

function operateCourse(operationName) {
    var $courseName = $('#courseName');
    var $studyCredit = $('#studyCredit');
	if ($.trim($courseName.val()).length == 0 || $.trim($studyCredit.val()).length == 0) {
		$.messager.alert("警告", "请确保红色*内容不为空！", "warning");
		return;
	}
    if (!validNumber($("#studyCredit").val())) {
        $.messager.alert("警告", "模块学分必须为数字！", "warning");
        return;
    }
	var courseStructure = $('#courseStructureDataGrid').datagrid('getSelected');
    var tempUrl = "course/add";
    if (operationName === '修改') {
        tempUrl = "course/update";
    } else {
        $("#courseId").val(-999); 
    }
	if ($('#oldIdNo').text() != null && $('#oldIdNo').text() == $("#courseName").val()) {
		 $.ajax({
             type: 'POST',
             data: {
                 "id": $("#courseId").val(),
                 "courseName": $("#courseName").val(),
                 "courseCode": $("#courseCode").val(),
                 "studyCredit": $("#studyCredit").val(),
                 "courseEvaluation": $("#courseEvaluation").val(),
                 "courseContent": $("#courseContent").val(),
                 "courseRequirement": $("#courseRequirement").val(),
                 "courseComment": $("#courseComment").val(),
                 "courseNumber": $("#courseNumber").val(),
                 "courseStructure.id": courseStructure.id,
                 "coursePeriod": $("#coursePeriod").val()},
             url: tempUrl,
             dataType: "json",
             cache: false,
             error: function (jqXHR, textStatus, errorThrown) {
                 $.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
             },
             success: function (data) {
                 if (true == data.result) {
                     $.messager.alert("操作提示", "课程信息操作完成！", "info", function () {
                         $('#operateCourseDialog').dialog("close");
                         gridReload($('#courseDataGrid'));
                     });
                 }
             }
         });
	} else {
		$.ajax({
	        type: 'POST',
	        data: { "courseName": $("#courseName").val() },
	        url: "course/exists",
	        dataType: "json",
	        cache: false,
	        success: function (data) {
	            if (true == data.result) {
	        		$.messager.alert("警告", "课程/模块已经存在！", "warning");
	            } else {
	                $.ajax({
	                    type: 'POST',
	                    data: {
	                        "id": $("#courseId").val(),
	                        "courseName": $("#courseName").val(),
	                        "courseCode": $("#courseCode").val(),
                            "studyCredit": $("#studyCredit").val(),
	                        "courseEvaluation": $("#courseEvaluation").val(),
	                        "courseContent": $("#courseContent").val(),
	                        "courseRequirement": $("#courseRequirement").val(),
	                        "courseComment": $("#courseComment").val(),
	                        "courseNumber": $("#courseNumber").val(),
	                        "courseStructure.id": courseStructure.id,
	                        "coursePeriod": $("#coursePeriod").val()},
	                    url: tempUrl,
	                    dataType: "json",
	                    cache: false,
	                    error: function (jqXHR, textStatus, errorThrown) {
	                        $.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
	                    },
	                    success: function (data) {
	                        if (true == data.result) {
	                            $.messager.alert("操作提示", "课程信息操作完成！", "info", function () {
	                                $('#operateCourseDialog').dialog("close");
	                                gridReload($('#courseDataGrid'));
	                            });
	                        }
	                    }
	                });
	            }
	        }
	    });
	}
}

function showDeleteCourseDialog(index) {
    $.messager.confirm("警告", "确定删除课程？", function (data) {
        if (data) {
        	var course = getSelectedRow('courseDataGrid', index);
        	$.ajax({
        		type: 'POST',
        		data: {
        			"courseId": course.id
        		},
        		url: "course/remove",
        		dataType: "json",
        		cache: false,
        		error: function (jqXHR, textStatus, errorThrown) {
        			$.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
        		},
        		success: function (data) {
        			if (true == data.result) {
    					$('#operateCourseDialog').dialog("close");
    					gridReload($('#courseDataGrid'));
        			} else {
                        $.messager.alert("操作提示", "删除课程信息异常！");
                    }
        		}
        	});
        }
    });
}

//##########################################################
function initShowRegion() {
	$('#courseEvaluationShow').attr("disabled", true);
	$('#courseContentShow').attr("disabled", true);
	$('#courseRequirementShow').attr("disabled", true);
	$('#courseCommentShow').attr("disabled", true);
	$('#courseNumberShow').attr("disabled", true);
	$('#coursePeriodShow').attr("disabled", true);
}

//##########################################################
function initTextbookGridData() {
    $('#textbookDataGrid').datagrid({
   	 	title: "教材",
        fitColumns: true,
        fit: true,
        idField: 'Id',
        sortName: 'Id',
        sortOrder: 'desc',
        rownumbers: true,
        singleSelect: true,
        border: false,
        toolbar: [
            {
                text: '新增',
                iconCls: 'icon-add',
                handler: function () {
                    showOperateTextbookDialog("新增");
                }
            }
        ],
        columns: [
            [
                {field: 'textbookName', title: '教材名称', align: 'center', width: 50},
                {field: 'operation', title: '操作', align: 'center', width: 80,
                    formatter: function (value, row, index) {
                        return "<a class='up' onclick='showOperateTextbookDialog(\"修改\", " + index + ");'>修改</a>" +
                            "<a class='re' onclick='showDeleteTextbookDialog(" + index + ");'>删除</a>";
                    }
                }
            ]
        ],
        rowStyler: function(index,row){  
            if (index % 2 == 1){  
                return 'background-color:#FFF8DC;';  
            }  
        },
        onLoadSuccess: function() {
        	changeStyle();
        }
    });
}

function showOperateTextbookDialog(operateName, index) {
    $('#oldIdNo').remove();
    var course = $('#courseDataGrid').datagrid('getSelected');
    if (course == null) {
		$.messager.alert("警告", "请首先选择一个课程/模块！", "warning");
    	return;
    }
    $('#operateTextbookDialog').dialog({
        title: operateName + "教材信息",
        width: 256,
        height: 124,
        modal: true,
        buttons: [
            {
                text: operateName,
                handler: function (params) {
                    operateTextbook(operateName);
                }
            },
            {
                text: '取消',
                handler: function () {
                    $('#operateTextbookDialog').dialog('close');
                }
            }
        ]
    });
    clearTextbookOldData();
    if (operateName == '修改') {
        var textbook = getSelectedRow('textbookDataGrid', index);
        $("#textbookId").val(textbook.id);
        $("#textbookName").val(textbook.textbookName);
        $('#operateTextbookDialog').append("<span id='oldIdNo'>" + textbook.textbookName + "</span>");
    }
}

function clearTextbookOldData() {
    $("#textbookId").val("");
    $("#textbookName").val("");
}
function operateTextbook(operationName) {
    var $textbookName = $('#textbookName');
	if ($.trim($textbookName.val()).length == 0) {
		$.messager.alert("警告", "请确保红色*内容不为空！", "warning");
		return;
	}
    var course = $('#courseDataGrid').datagrid('getSelected');
    var tempUrl = "textbook/add";
    if (operationName === '修改') {
        tempUrl = "textbook/update";
    } else {
        $("#textbookId").val(-999);
    }
	if ($('#oldIdNo').text() != null && $('#oldIdNo').text() == $("#textbookName").val()) {
		$.ajax({
            type: 'POST',
            data: {
                "id": $("#textbookId").val(),
                "courseId": course.id,
                "textbookName": $("#textbookName").val()
            },
            url: tempUrl,
            dataType: "json",
            cache: false,
            error: function (jqXHR, textStatus, errorThrown) {
                $.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
            },
            success: function (data) {
                if (true == data.result) {
                    $.messager.alert("操作提示", "教材信息操作完成！", "info", function () {
                        $('#operateTextbookDialog').window("close");
                        gridReload($('#textbookDataGrid'));
                    });
                }
            }
        });
	} else {
		$.ajax({
	        type: 'POST',
	        data: { 
	            "textbookName": $("#textbookName").val() },
	        url: "textbook/exists",
	        dataType: "json",
	        cache: false,
	        success: function (data) {
	            if (true == data.result) {
	        		$.messager.alert("警告", "教材已经存在！", "warning");
	            } else {
	                $.ajax({
	                    type: 'POST',
	                    data: {
	                        "id": $("#textbookId").val(),
	                        "courseId": course.id,
	                        "textbookName": $("#textbookName").val()
	                    },
	                    url: tempUrl,
	                    dataType: "json",
	                    cache: false,
	                    error: function (jqXHR, textStatus, errorThrown) {
	                        $.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
	                    },
	                    success: function (data) {
	                        if (true == data.result) {
	                            $.messager.alert("操作提示", "教材信息操作完成！", "info", function () {
	                                $('#operateTextbookDialog').window("close");
	                                gridReload($('#textbookDataGrid'));
	                            });
	                        }
	                    }
	                });
	            }
	        }
	    });
	}
}

function showDeleteTextbookDialog(index) {
    $.messager.confirm("警告", "确定删除选中教材？", function (data) {
        if (data) {
        	var textbook = getSelectedRow('textbookDataGrid', index);
        	$.ajax({
        		type: 'POST',
        		data: {
        			"textbookId": textbook.id
        		},
        		url: "textbook/remove",
        		dataType: "json",
        		cache: false,
        		error: function (jqXHR, textStatus, errorThrown) {
        			$.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
        		},
        		success: function (data) {
        			if (true == data.result) {
    					gridReload($('#textbookDataGrid'));
        			} else {
                        $.messager.alert("操作提示", "删除教材信息异常！");
                    }
        		}
        	});
        }
    });
}